package org.wzys.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wzys.Mapper.UserMapper;
import org.wzys.Pojo.LoginInfo;
import org.wzys.Pojo.PageResult;
import org.wzys.Pojo.User;
import org.wzys.Pojo.UserQueryparm;
import org.wzys.Service.UserService;
import org.wzys.utils.JwtUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult getpageinfo(UserQueryparm userQueryparm) {
        //实现分页查询
        //1. 设置PageHelper分页参数
        PageHelper.startPage(userQueryparm.getPagenum(), userQueryparm.getPageSize());
        //2. 执行查询
        List<User> UserList = userMapper.list(userQueryparm);
        //3. 封装分页结果
        Page<User> p = (Page<User>) UserList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void delete(List<Integer> ids) {
        userMapper.delete(ids);
    }

    @Override
    public void add(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.add(user);
    }

    @Override
    public User getbyid(Integer id) {
        return userMapper.getbyid(id);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public LoginInfo login(User user) {
        User empLogin = userMapper.getUsernameAndPassword(user);
        if(empLogin != null){
            log.info("用户密码认证正确，返回属性值和JWTtoken");
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("id", empLogin.getId());
            dataMap.put("username", empLogin.getUsername());

            String jwt = JwtUtils.generateJwt(dataMap);
            return new LoginInfo(empLogin.getId(), empLogin.getUsername(), empLogin.getPassword(), jwt, empLogin.getRole());
        }
        log.info("SQL语句查询失败，没有对应用户{}，或者有对应的错误密码{}", user.getUsername(), user.getPassword());
        return null;
    }

    @Override
    public void register(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.register(user);
    }
}
